﻿using Bnbjoy.Business.Abstract;
using Bnbjoy.Business.Common;
using Bnbjoy.Business.Constants;
using Bnbjoy.Business.Model.Dashboard;
using Bnbjoy.Domain.Abstract;
using Bnbjoy.Domain.Entities;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bnbjoy.Business.Concrete
{
    public class OrderService : IOrderService
    {
        IOrderRepository _repository;

        public OrderService(IOrderRepository orderRepository)
        {
            this._repository = orderRepository;
        }

        public async Task<OrderResponse> NewOrder(OrderType orderType, Order order, IEnumerable<Customer> customers, IEnumerable<OrderSpending> spendings) 
        {
            var insertResult = await _repository.InsertOrder(order, customers, spendings);

            if (insertResult)
            {
                dynamic createdOrder = await _repository.FindOrder(order.OrderId);
                var response = new OrderResponse();
                response.order = createdOrder.Order;
                response.customers = createdOrder.Customers;
                response.spendings = createdOrder.Spendings;
                return response;
            }
            else 
            {
                return null;
            }
        }

        public async Task<string> FetchMobileArea(string mobileNumber)
        {
            var result = await _repository.ObtainMobileArea(mobileNumber);
            return result;
        }

        public async Task<QueryAvailableRoomsResponse> FetchAvailableRooms(QueryAvailableRoomsParam param) 
        {
            int total = await this._repository.TotalRoomCount(param.BnbId);

            IEnumerable<dynamic> result = await this._repository.RetrieveAvailableRooms(param.BnbId, param.FromDate);
            QueryAvailableRoomsResponse response = new QueryAvailableRoomsResponse();
            string employeesInfoJson = JsonConvert.SerializeObject(result);
            response.Pairs = JsonConvert.DeserializeObject<IEnumerable<DateRoomsPair>>(employeesInfoJson);
            foreach (var p in response.Pairs) 
            {
                p.RoomCount = total - p.RoomCount;
            }

            response.Total = total;

            return response;
        }

        public void Dispose()
        {

        }
    }
}
